﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;
using System.Diagnostics;

namespace MySCM.Common.Log
{
    public class StaticLogger
    {
        static FileStream fs;
        static string desLogFilename;
        static string errLogFilename;
        static string usrLogFilename;


        static StaticLogger()
        {
            string appRoot = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location + "..");
            desLogFilename = appRoot + @"\Logs\Design.log";
            errLogFilename = appRoot + @"\Logs\Error.log";
            usrLogFilename = appRoot + @"\Logs\User.log";

            // If the folder (Logs) does not exist, create it
            if (!Directory.Exists(appRoot + @"\Logs"))
            {
                Directory.CreateDirectory(appRoot + @"\Logs");
            }
        }
        

        // logType: Design, Error, User (same as the log file name)
        // level  : User defined/picked names to distinguish the importance of logs, i.e., Info, Warning, Urgent
        public static void WriteLog(string logType, string level, string logMessage)
        {
            try
            {
                switch (logType.ToUpper())
                {
                    case "DESIGN":
                        fs = new FileStream(desLogFilename, FileMode.Append);
                        break;
                    case "ERROR":
                        fs = new FileStream(errLogFilename, FileMode.Append);
                        break;
                    case "USER":
                        fs = new FileStream(usrLogFilename, FileMode.Append);
                        break;
                    default:
                        fs = new FileStream(desLogFilename, FileMode.Append);
                        break;
                }
                StreamWriter sw = new StreamWriter(fs);
                StackFrame sf = new StackFrame(1, true);
                sw.WriteLine(DateTime.Now.ToString() + " *** " + level + " *** " + sf.GetFileName() + " (" + sf.GetFileLineNumber() + ") *** " + sf.GetMethod() + " *** " + logMessage);
                sw.Flush();
                sw.Close();
                fs.Close();
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
}
